<div>
    <div id="{{ plot_div_id }}" class="plotly-graph-div" style="height:100%; width:100%;"></div>
    <script type="text/javascript">
        require(['https://cdn.plot.ly/plotly-2.12.1.min.js'], function(Plotly) {
            Plotly.newPlot(
                "{{ plot_div_id }}",
                {{ plot|tojson|safe }}
            ).then(function() {
                var gd = document.getElementById('{{ plot_div_id }}');
                var x = new MutationObserver(function (mutations, observer) { {
                        var display = window.getComputedStyle(gd).display;
                        if (!display || display === 'none') { {
                            Plotly.purge(gd);
                            observer.disconnect();
                        } }
                } });

                // Listen for the removal of the full notebook cells
                var notebookContainer = gd.closest('#notebook-container');
                if (notebookContainer) { {
                    x.observe(notebookContainer, {childList: true});
                } }

                // Listen for the clearing of the current output cell
                var outputEl = gd.closest('.output');
                if (outputEl) { {
                    x.observe(outputEl, {childList: true});
                } }
            })
        });
    </script>
</div>